package com.huika.renrench.control.my.activity;

import java.util.ArrayList;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.huika.lib.bitmap.core.DisplayImageOptions;
import com.huika.lib.bitmap.core.ImageLoader;
import com.huika.lib.bitmap.core.ImageLoaderConfiguration;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.my.bank.activity.BankInfoActivity;
import com.huika.renrench.control.my.bank.activity.MyBankCardActivity;
import com.huika.renrench.control.my.pay.llpay.LianlPay;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.BankCardBean;
import com.huika.renrench.support.bean.LianLianBean;
import com.huika.renrench.view.TitleBarHelper;

/**
 * 
 * @description：充值
 * @author zc
 * @date 2015年6月2日 上午11:56:00
 */
public class RechargeActivity extends BaseAct implements Listener<RequestResult<ArrayList<BankCardBean>>> {

	private View layout1;
	private ImageView bank_logo;
	private TextView bank_name;
	private TextView last_no;
	private EditText money_detail;
	private Button confirm;
	private BankCardBean bankCardBean;
	private String userId;
	private DisplayImageOptions options;
	private LianLianBean bean;
	private Dialog dialog;
	private boolean isFresh = false;
	
	@Override
	protected void initData() {
		super.initData();
		TitleBarHelper barHelper = new TitleBarHelper(this, -1);
		barHelper.setLeftMsg("我的");
		barHelper.setTitleMsg("充值");
		userId = GlobalApp.userModel.getUserId();
		options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.icon_default_small)
				// resource or drawable
						.showImageForEmptyUri(R.drawable.icon_default_small).showImageOnFail(R.drawable.icon_default_small).cacheInMemory(true)// 开启内存缓存
						.cacheOnDisk(true) // 开启硬盘缓存
						.resetViewBeforeLoading(true).build();
	}
	
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_recharge);
	}
	
	@Override
	protected void initWidget() {
		super.initWidget();
		layout1 = findViewById(R.id.layout1);
		bank_logo = (ImageView) findViewById(R.id.bank_logo);
		bank_name = (TextView) findViewById(R.id.bank_name);
		last_no = (TextView) findViewById(R.id.last_no);
		money_detail = (EditText) findViewById(R.id.money_detail);
		confirm = (Button) findViewById(R.id.confirm);
		money_detail.addTextChangedListener(new MyWatcher());
		layout1.setOnClickListener(this);
		confirm.setOnClickListener(this);
		getMyBankCardList(userId, 1 , 1);
	}
	
	class MyWatcher implements TextWatcher {
		String tempStr;
		
		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			tempStr = s.toString();
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if(!checkInputMoney(s.toString())) {
				money_detail.setText(tempStr);
				money_detail.setSelection(money_detail.length());
				return;
			} else if(s.length() > 1 && s.toString().substring(0, 1).equals("0") && !s.toString().startsWith("0.")) {
				money_detail.setText(s.toString().substring(1));
				money_detail.setSelection(money_detail.length());
			}
		}
		
	}
	
	private boolean checkInputMoney(String money) {
		String patten = "^[0-9]{0,8}?$";
		return money.equals("")?true:money.matches(patten);
	}
	/**
	 * 
	 * @description：判断是否可以提交的金额
	 * @author zc
	 * @date 2015年6月23日 下午3:11:14
	 */
	private boolean canSubmitMoney(String money) {
		String patten = "^[0-9]+(.[0-9]{1,2})?$";
		return money.matches(patten);
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		getMyBankCardList(userId, 1, 1);
	}
	
	private void warning() {
		dialog = MMAlert.createShowCenterDialog(context, "温馨提示", "您还没绑定银行卡，请前往绑定", "忽略", "立即前往", new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		}, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showActivity(RechargeActivity.this, MyBankCardActivity.class);
			}
		});
		dialog.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss(DialogInterface dialog) {
				if(!isFresh) {
					finish();
				}
			}
		});
		dialog.show();
	}
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch(v.getId()) {
			case R.id.confirm:
				checkInput();
				break;
			case R.id.layout1:
				if(bankCardBean != null) {
					Intent intent = new Intent(this, BankInfoActivity.class);
					intent.putExtra("bankCardBean", bankCardBean);
					intent.putExtra("flag", 1);
					startActivityForResult(intent, 100);
				} else {
					ToastMsg.showToastMsg(this, "网络不稳定，请稍后再试!");
				}
				break;
		}
	}
	
	private void checkInput() {
		if(money_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入充值金额");
			return;
		} else if(!canSubmitMoney(money_detail.getText().toString())) {
			ToastMsg.showToastMsg(this, "您输入的格式不正确，请重新输入");
			money_detail.setText("");
			return;
		}
		else if(Double.parseDouble(money_detail.getText().toString()) < 100)
		{
			ToastMsg.showToastMsg(this, "充值金额最低为100元");
			return;
		}
		if(bankCardBean != null) {
			
			insertOrder(userId, money_detail.getText().toString(), bankCardBean.getRealName(), GlobalApp.userModel.getIdCard(), 
					bankCardBean.getRealName(), bankCardBean.getCardNumber());
		} else {
			ToastMsg.showToastMsg(this, "网络不稳定，请稍后再试!");
		}
	}

	private void insertOrder(String userId, String amount, String realName, String identityCard, String acctName, String cardNo) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("amount", amount);
		ajaxParams.putCommonTypeParam("realName", realName);
		ajaxParams.putCommonTypeParam("identityCard", identityCard);
		ajaxParams.putCommonTypeParam("acctName", acctName);
		ajaxParams.putCommonTypeParam("cardNo", cardNo);
		FormResultRequest<LianLianBean> request = new FormResultRequest<LianLianBean>(UrlConstants.INSERTORDER, new Listener<RequestResult<LianLianBean>>() {

			@Override
			public void onResponse(RequestResult<LianLianBean> arg0) {
				dismissLoadingDialog();
				if(arg0.flag == 1) {
					bean = arg0.getRs();
					new LianlPay(RechargeActivity.this, bankCardBean.getRealName()).pay(bean);
				}
			}
		}, this, new TypeToken<RequestResult<LianLianBean>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	/**
	 * 
	 * @description：获取我的银行卡列表
	 * @author zc
	 * @date 2015年6月2日 下午5:44:17
	 */
	private void getMyBankCardList(String userId, int pageNo, int pageSize) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("pageNo", pageNo);
		ajaxParams.putCommonTypeParam("pageSize", pageSize);
		FormResultRequest<ArrayList<BankCardBean>> request = new FormResultRequest<ArrayList<BankCardBean>>(UrlConstants.GETMYBANKCARDLIST, this, this, new TypeToken<RequestResult<ArrayList<BankCardBean>>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	

	@Override
	public void onResponse(RequestResult<ArrayList<BankCardBean>> arg0) {
		dismissLoadingDialog();
		if(arg0.flag == 1 ) {
			if(arg0.getRs().size() > 0) {
				ImageLoader imageLoader = ImageLoader.getInstance();
				imageLoader.init(ImageLoaderConfiguration.createDefault(this));
				bankCardBean = arg0.getRs().get(0);
				imageLoader.displayImage(bankCardBean.getLogoImg(), bank_logo, options);
				bank_name.setText(bankCardBean.getBankName());
				last_no.setText("尾号" + bankCardBean.getCardNumber().substring(bankCardBean.getCardNumber().length() - 4));
			} else {
				warning();
			}
		}
	}

}
